package com.xingchi.tornado.security.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xingchi.tornado.basic.Result;
import com.xingchi.tornado.core.code.SecurityCode;
import com.xingchi.tornado.security.exception.VerityCodeErrorException;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败处理器
 *
 * @author xingchi
 * @date 2025/3/9 21:03
 */
public class DefaultAuthenticationFailureHandler implements AuthenticationFailureHandler {

    private final ObjectMapper objectMapper;

    public DefaultAuthenticationFailureHandler(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        String errorMessage = "认证失败";
        if (exception instanceof BadCredentialsException) {
            errorMessage = "用户名或密码错误";
        } else if (exception instanceof AccountExpiredException) {
            errorMessage = "账户已过期";
        } else if (exception instanceof UsernameNotFoundException) {
            errorMessage = "用户不存在";
        } else if (exception instanceof CredentialsExpiredException) {
            errorMessage = "密码已过期";
        } else if (exception instanceof VerityCodeErrorException) {
            errorMessage = "验证码错误";
        }

        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        response.setContentType("application/json; charset=utf-8");

        Result<Object> fail = Result.fail(SecurityCode.UNAUTHORIZED, errorMessage);
        response.getWriter().print(objectMapper.writeValueAsString(fail));
    }
}
